﻿using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace CloudShot
{
	static class Program
	{
		static Mutex mutex = new Mutex(true, "CloudShot by name1ess0ne");

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main()
		{
			string errorFile = Path.Combine(Application.LocalUserAppDataPath, "Error.log");
			Trace.AutoFlush = true;
			Trace.Listeners.Add(new TextWriterTraceListener(errorFile));

			// Add the event handler for handling UI thread exceptions to the event.
			Application.ThreadException += UIThreadException;

			// Set the unhandled exception mode to force all Windows Forms errors to go through
			// our handler.
			Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

			// Add the event handler for handling non-UI thread exceptions to the event. 
			AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

			if (mutex.WaitOne(TimeSpan.Zero, true))
			{
				Application.EnableVisualStyles();
				Application.SetCompatibleTextRenderingDefault(false);
				//var form = new MainForm();
				//form.Shot( ShotType.Region, false );

				Application.Run(new MainForm());
				mutex.ReleaseMutex();
			}
			else
			{
				MessageBox.Show("CloudShot already running.\nAt the same time may be running only one instance.",
					Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
		}

		private static void UIThreadException(object sender, ThreadExceptionEventArgs e)
		{
			ShowThreadExceptionDialog(Application.ProductName, e.Exception);
			Application.Exit();
		}

		private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			Exception ex = (Exception)e.ExceptionObject;
			ShowThreadExceptionDialog(Application.ProductName, ex);
			Application.Exit();
		}

		// Creates the error message and displays it.
		private static void ShowThreadExceptionDialog(string title, Exception ex)
		{
			string errorMessage = string.Format("Error: {0}\r\nDate: {1}\r\nStackTrace: {2}\r\n", ex.Message, DateTime.Now, ex.StackTrace);
			Trace.WriteLine(errorMessage);

			string errorMsg = "An application error occurred. Please contact the developer with the following information:\n\n";
			errorMsg = errorMsg + ex.Message + "\n\nStack Trace:\n" + ex.StackTrace;
			MessageBox.Show(errorMsg, title, MessageBoxButtons.OK, MessageBoxIcon.Stop);
		}
	}
}
